import { Component, OnInit} from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var echarts: any;
declare var Viewer: any;
@Component({
	selector: 'sa-car-measure',
	templateUrl: './car-measure.component.html',
	styleUrls: ['./car-measure.component.css']
})
export class CarMeasureComponent implements OnInit {
    tableData = []; //table数据    侧挂链条
	totalCount: number = 0; //分页总条数   侧挂链条
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	tableParam: any = {
        useTypeL2: '0213',
        companyName: '',
        companyId: '',
        carNumber: '',
        deviceId: '',
        userName: '',//录入人员
        startTime: '',
        endTime: '',
        searchKey: '',
        schemeMatch: '',
        auditStatus: '',
        type: '',//是否导出  空:否  1:是
	}
	userList: any = [];//用户数据List
	
	paramFormat:any = {
        id:'id',
        text:'name',
    }
	carList:any = []; //量车数据
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}
	ngOnInit() {
	    this.getCarList();
		this.initAllUser().then(() => {
			this.selectUserName();
		});
		this.load();
	}
	// 量车车辆数据
    getCarList(){
        this.jsonApiService.http("deviceInstallRecord/getCarNumber.html",null).subscribe(data => {
            if(data.success){
                let temArr = [];
                for(let item of data.data){
                    let obj = {
                        id: item,
                        name: item
                    }
                    temArr.push(obj);
                }
                this.carList = temArr;
            }
        })
    }
	ngOnDestroy() {
		document.onclick = null;
	}
	//公司选中回调
    companySelected(data) {
        this.tableParam.companyId = data.companyId;
        this.tableParam.companyName = data.companyName;
    }
    carSelected(data){
        this.tableParam.carNumber = data.text;
    }
	// 接收子组件传递过来的数据 
    getSelectTableTime(time) {
        this.tableParam.startTime = time.startTime;
        this.tableParam.endTime = time.endTime;
    } 
	//擦除用户所选值
	delUserName() {
		this.tableParam.userName = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2').val("");
		$("#select2-userNameSelect2-container").empty();
		$("#select2-userNameSelect2-container").attr("title", "");
		$("#select2-userNameSelect2-container").prepend(str);
	}
	//初始化select2 选项
	selectUserName() {
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				$("#userNameSelect2").select2({
					language: "zh-CN",
					placeholder: "请选择",
					allowClear: true,
					data: this.userList,//为Select添加数据
					templateResult: this.formatRepo
				}).on("select2:select", function (e) {
					var data = e.params.data;
					that.tableParam.userName = data.text;
				});
			})
		})
	}
	//select2 格式回调函数
	formatRepo(state) {
		if (!state.id) { return state.text };
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//拉取
	initAllUser() {
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("user/getUserList.html", null).subscribe(data => {
				if (data.success) {
					var userList = data.data;
					var selectdata = [];
					for (var i = 0; i < userList.length; i++) {
						var obj = {
							id: userList[i].userName,
							text: userList[i].name,
						}
						selectdata[i] = obj;
					}
				}
				that.userList = selectdata;
				resolve();
			})
		})
	}
	//table刷新
	refresh() {
		this.load();
	}
	//表格搜索
	table_search() {
		this.curPage = 1;
		this.tableParam.searchKey = common.stringTrim(this.tableParam.searchKey);
		this.load();
	}
    //分页回调
    paginate(e) {
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }
    btnClick(type){
        this.tableParam.useTypeL2 = type;
        this.curPage = 1;
        this.load();
    }
	//初始化加载list数据
	load() {
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
			    carNumber: this.tableParam.carNumber,
			    useTypeL2: this.tableParam.useTypeL2,
                startTime: this.tableParam.startTime,
                endTime: this.tableParam.endTime,
                companyId: this.tableParam.companyId,//查询公司参数
                enterMan: this.tableParam.userName,//录入人员
                searchKey: this.tableParam.searchKey,
                schemeMatch: this.tableParam.schemeMatch,
                auditStatus: this.tableParam.auditStatus,
                type: '',//是否导出  空:否  1:是
            },
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("deviceInstallRecord/vehiclesList.html", reqdata).subscribe(result => {
    	    this.tableData = result.exhibitDatas || [];
            this.totalCount = result.recordCount;
		})
	}
	// 导出
	table_export(){
	    // this.tableParam.reportDate = $('#reportDate').val();
	    let data = {
            pageSize: this.pageSize,
            nowPage: this.curPage,
            parameters: {
                carNumber: this.tableParam.carNumber,
                useTypeL2: this.tableParam.useTypeL2,
                startTime: this.tableParam.startTime,
                endTime: this.tableParam.endTime,
                companyId: this.tableParam.companyId,//查询公司参数
                enterMan: this.tableParam.userName,//录入人员
                searchKey: this.tableParam.searchKey,
                schemeMatch: this.tableParam.schemeMatch,
                auditStatus: this.tableParam.auditStatus,
                type: '1',//是否导出  空:否  1:是
            },
        }
        let timeCheck = common.correctTime(data.parameters, ['useTypeL2', 'type'])
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
	    common.exprotDataFile(data, "gridPager", config.BaseURL+'deviceInstallRecord/vehiclesList.html');
	}
	// 删除功能
	deleteRow(row){
		this.jsonApiService.confirm_message('删除数据将永久删除，确认要删除?').then(()=>{
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("deviceInstallRecord/deletedEnvironmentalById.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
	// 匹配
	drawingsMatch(){
	    this.jsonApiService.http_obj("deviceInstallRecord/matchDrawing.html", {useTypeL2:this.tableParam.useTypeL2}).subscribe(data => {
            this.jsonApiService.message(data.message);
            if(data.success){
                this.load();
            }
        })
	}
	// 单个数据匹配
	matchRow(row){
	    this.jsonApiService.http_obj("deviceInstallRecord/matchById.html", {id:row.id}).subscribe(data => {
            this.jsonApiService.message(data.message);
            if(data.success){
                this.load();
            }
        })
	}
	// 匹配详情查看
	matchDetailData:any = [];
	matchDetailTitle = '';
	matchView(row,modal,name){
	    this.matchDetailTitle = name;
	    modal.show();
	    this.jsonApiService.http_obj("deviceInstallRecord/queryMeasureProgramById.html", {id:row.id}).subscribe(data => {
            if(data.success){
                this.matchDetailData = data.data;
            }else{
                this.jsonApiService.message(data.message);
            }
        })
	}
	// 匹配详情关闭
	closeMatchDetailModal(modal){
	    modal.hide();
	}
	// 导出加工
	exportMatch(modal){
	    modal.show();
	}
	/**
	 *  审核部分 ===================================================================================================================
	 */
	auditForm:any = {
	    id:'',
	    status:'1',
	    describe:'',
	}
	// 审核
	checkRow(row,modal){
	    modal.show();
	    this.auditForm.id = row.id;
	}
	// 审核取消
	cancelAudit(modal){
	    modal.hide();
	    this.auditForm = {
            id:'',
            status:'1',
            describe:'',
        }
	}
	// 审核提交
	auditSubmit(modal){
	    this.jsonApiService.http_obj("deviceInstallRecord/auditRecord.html", this.auditForm).subscribe(data => {
            this.jsonApiService.message(data.message);
            if(data.success){
                this.cancelAudit(modal);
                this.load();
            }
        })
	}
	/**
	 *  导出加工模块======================================================================================================================= 
	 */
	exportProjectForm:any = {
	    companyId: '',
	    startTime: '',
	    endTime: '',
	    useTypeL2: '',
	}
	specifyId:any = {
        picker1:'datetimepicker3',
        picker2:'datetimepicker4'
    }
	getSelectTimeForm(time){
	    this.exportProjectForm.startTime = time.startTime;
        this.exportProjectForm.endTime = time.endTime;
	}
	companySelectedForm2(data){
	    this.exportProjectForm.companyId = data.companyId;
//      this.exportProjectForm.companyName = data.companyName;
	}
	cancelexportProject(modal){
	    modal.hide();
	}
	// 导出加工
	exportProject(modal,type){
	    if(!this.exportProjectForm.companyId){
	        this.jsonApiService.message('请选择公司名称');
	        return;
	    }
	    if(!this.exportProjectForm.startTime || !this.exportProjectForm.endTime){
	        this.jsonApiService.message('请选择时间范围');
            return;
	    }
	    let timeCheck = common.correctTimeParams(this.exportProjectForm.startTime,this.exportProjectForm.endTime,0);
        if(!timeCheck.status){
            this.jsonApiService.message(timeCheck.message);
            return;
        }
        if(!this.exportProjectForm.useTypeL2){
            this.jsonApiService.message('请选择车型');
            return;
        }
	    let Url = 'deviceInstallRecord/exportProcess.html';
	    if(type == '2'){
	        Url = 'deviceInstallRecord/exportProject.html';
	    }
	    var form = $("<form>"); //定义一个form表单
        form.attr("style", "display:none");
        form.attr("target", "");
        form.attr("method", "post");
        form.attr("action", config.BaseURL + Url);
        var fileInput1 = $("<input>");
        fileInput1.attr("type", "hidden");
        fileInput1.attr("name", "companyId"); //设置属性的名字
        fileInput1.attr("value", this.exportProjectForm.companyId); //设置属性的值
        var fileInput2 = $("<input>");
        fileInput2.attr("type", "hidden");
        fileInput2.attr("name", "startTime"); //设置属性的名字
        fileInput2.attr("value", this.exportProjectForm.startTime); //设置属性的值
        var fileInput3 = $("<input>");
        fileInput3.attr("type", "hidden");
        fileInput3.attr("name", "endTime"); //设置属性的名字
        fileInput3.attr("value", this.exportProjectForm.endTime); //设置属性的值
        var fileInput4 = $("<input>");
        fileInput4.attr("type", "hidden");
        fileInput4.attr("name", "useTypeL2"); //设置属性的名字
        fileInput4.attr("value", this.exportProjectForm.useTypeL2); //设置属性的值
        $("body").append(form); //将表单放置在web中
        form.append(fileInput1);
        form.append(fileInput2);
        form.append(fileInput3);
        form.append(fileInput4);
        form.submit(); //表单提交   
	}
	// 编辑
	editRowData:any; // 储存编辑数据
	editRow(row,modal){
	    this.editRowData = JSON.parse(JSON.stringify(row));
	    modal.show();
	}
	// 关闭编辑
	closecarMeasureModal(modal){
	    modal.hide()
	}
	// 公司选中回传
	companySelectedForm(data){
	    this.editRowData.companyId = data.companyId;
	    this.editRowData.companyName = data.companyName;
	}
	// 编辑提交
	carMeasureSubmit(modal){
	    let reqdata = {
	        carHeadBrand: this.editRowData.carHeadBrand,
            carHeadBrandUrl: this.editRowData.carHeadBrandUrl,
            carNumber: this.editRowData.carNumber,
            carNumberUrl: this.editRowData.carNumberUrl,
            carTailBrand: this.editRowData.carTailBrand,
            carTailBrandUrl: this.editRowData.carTailBrandUrl,
            carTailShelfUrl: this.editRowData.carTailShelfUrl,
            chainWidth: this.editRowData.chainWidth,
            chainWidthUrl: this.editRowData.chainWidthUrl,
            companyId: this.editRowData.companyId,
            companyName: this.editRowData.companyName,
            downBucketTime:this.editRowData.downBucketTime,
            fixDistance: this.editRowData.fixDistance,
            fixDistanceUrl: this.editRowData.fixDistanceUrl,
            id: this.editRowData.id,
            measureInfoList: JSON.stringify(this.editRowData.measureInfoList),
            remark: this.editRowData.remark,
            upBucketTime: this.editRowData.upBucketTime,
            useTypeL1: this.editRowData.useTypeL1,
            useTypeL2: this.editRowData.useTypeL2,
	    }
	    this.jsonApiService.http_obj("deviceInstallRecord/editCarMeasure.html", reqdata).subscribe(data => {
            this.jsonApiService.message(data.message);
            if(data.success){
                this.load();
                modal.hide()
            }
        })
	}
	// 图片查看
    activeImg:any = {
        title:'',
        url:''
    }
    imgView(imageUrl,name,modal){
        this.activeImg.title = name;
        this.activeImg.url = imageUrl;
        modal.show();
    }
    // 图片关闭
    imgClose(modal){
        modal.hide();
    }
    //图片放大
    isViewer:Boolean = false;
    viewer:any;
    bigimg(ele){
        if(this.isViewer && $(".viewer-container").length >0){
            if(this.isViewer && $(".viewer-container").length >0){
                this.viewer.destroy();
            }
            System.import('assets/js/viewer/viewer.js').then(
                ()=>{System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
                    ()=>{System.import('assets/js/viewer/viewer.css').then(()=>{
                        this.showImg(ele);
                    })
                })
            })
        }else{
            this.showImg(ele);
        }

    }
    showImg(ele){
        var that = this;
        var imgList = $("."+ele)[0];
        this.viewer = new Viewer(imgList, {
            url: 'src',
            title: function (image) {
                return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')' ; 
            },
        });
        this.isViewer = true;
    }
    /**
     * 量车尺寸图============================================================================== 
     */
    activeImgList:any = {
        title:'',
        templateImg:[],
        img:'',
        measureInfoList:[],
    }
    imgListView(row,type,modal){
        this.activeImgList = {
            title:'',
            templateImg:[],
            img:'',
            measureInfoList:[],
        }
        switch (type){
        	case '0211':
        	    this.activeImgList.title = '后挂双桶';
        	    this.activeImgList.templateImg.push('assets/img/environmental/0211-01.png');
        	    this.activeImgList.templateImg.push('assets/img/environmental/0211-02.png');
                this.activeImgList.templateImg.push('assets/img/environmental/0211-03.png');
//      	    this.activeImgList.img = 'assets/img/environmental/0211.jpg';
        		break;
        	case '0213':
                this.activeImgList.title = '侧挂链条';
                this.activeImgList.templateImg.push('assets/img/environmental/0213-01.png');
//              this.activeImgList.img = 'assets/img/environmental/0213.jpg';
                break;
            case '0214':
                this.activeImgList.title = '侧挂拉杆';
                this.activeImgList.templateImg.push('assets/img/environmental/0214-01.jpg');
//              this.activeImgList.img = 'assets/img/environmental/0214.jpg';
                break;
        	default:
        		break;
        }
        this.activeImgList.img = row.carTailShelfUrl;
        this.activeImgList.measureInfoList = row.measureInfoList;
        modal.show();
    }
    imgListClose(modal){
        modal.hide();
    }
}